package cn.dapeng.interview;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Semaphore;

/**
 * 实现一个容器，提供两个方法 add和size
 * 写两个线程 线程1添加10个元素，线程2实现监控元素的个数，当个数到5个时，线程2给出提示并结束??
 * <p>
 * <p>
 * <p>
 * 这种写法实现不了
 */
public class Taobao_Semaphore {

    volatile List<Integer> list = Collections.synchronizedList(new ArrayList<>());

    public synchronized void add(int num) {
        list.add(num);
    }

    public synchronized int size() {
        return list.size();
    }

    static Thread t1 = null, t2 = null;

    public static void main(String[] args) {
        Taobao_Semaphore taobao = new Taobao_Semaphore();

        Semaphore semaphore = new Semaphore(1);

        t1 = new Thread(() -> {
            try {
                semaphore.acquire();
                for (int i = 0; i < 5; i++) {
                    taobao.add(i);
                    System.out.println("add" + i);
                }
                semaphore.release();

                t2.start();
                t2.join();

                semaphore.acquire();
                for (int i = 5; i < 10; i++) {
                    taobao.add(i);
                    System.out.println("add" + i);
                }
                semaphore.release();
            } catch (Exception e) {
                System.err.println(e);
            }

        }, "t1");

        t2 = new Thread(() -> {
            try {
                semaphore.acquire();
                System.out.println("t2 end啊");
                semaphore.release();
            } catch (Exception e) {
                System.err.println(e);
            }
        }, "t2");
        t1.start();
        //SleepingUtil.sleep(1, TimeUnit.SECONDS);
        //t2.start();
    }
}
